package com.llu.aesAndDes;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;

public class DESTest {
    public static void main(String[] args) throws Exception {
        String plainText = "Hello, World!";
        String key = "12345678"; // 8字节密钥
        String iv = "87654321";  // 8字节初始化向量

        // 加密
        String encryptedText = encrypt(plainText, key, iv, "DES/CBC/PKCS5Padding");
        System.out.println("Encrypted (Base64): " + encryptedText);

        // 解密
        String decryptedText = decrypt(encryptedText, key, iv, "DES/CBC/PKCS5Padding");
        System.out.println("Decrypted: " + decryptedText);
    }

    public static String encrypt(String plainText, String key, String iv, String transformation) throws Exception {
        // 创建DESKeySpec
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());

        // 创建SecretKeyFactory
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

        // 生成SecretKey
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 创建Cipher对象，指定使用的加密模式和填充方式
        Cipher cipher = Cipher.getInstance(transformation);

        // 初始化Cipher对象为加密模式，并指定密钥和初始化向量
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

        // 加密
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));

        // 将密文字节数组转换为Base64编码字符串
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, String key, String iv, String transformation) throws Exception {
        // 创建DESKeySpec
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());

        // 创建SecretKeyFactory
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

        // 生成SecretKey
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 创建Cipher对象，指定使用的加密模式和填充方式
        Cipher cipher = Cipher.getInstance(transformation);

        // 初始化Cipher对象为解密模式，并指定密钥和初始化向量
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

        // 解密
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

        // 将密文字节数组转换为字符串
        return new String(decryptedBytes, "UTF-8");
    }
}

